package ai.tuobot.sdk.util

import ai.tuobot.sdk.inf.TextEventProcessCallB
import android.util.Log
import kotlinx.coroutines.suspendCancellableCoroutine
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import kotlin.coroutines.resume

object ProcessTextEvent {

    private val TAG = "ProcessTextEvent"

    private lateinit var textEventProcessCallB: TextEventProcessCallB

    fun onJsonTextEvent(preJsonStr: String, textEventProcessCallB: TextEventProcessCallB) {
        synchronized(ProcessTextEvent.javaClass){
            this.textEventProcessCallB = textEventProcessCallB
            try {
                val eventConJsonArr = getEventJsonArray(preJsonStr)
                for (i in 0 until eventConJsonArr.length()) {
                    val jsonObj = eventConJsonArr.get(i)
                    val eventType = (jsonObj as JSONObject).getString("event_type")
                    Log.d(TAG,"eventType:$eventType")
                    this.textEventProcessCallB.onEventCallB(eventType,jsonObj)
                    Log.d(TAG,"this.textEventProcessCallB: ${this.textEventProcessCallB}")
                }
            } catch (e: JSONException) {
                Log.e(TAG,e.message.toString())
                // 处理 JSON 解析异常
                e.printStackTrace()
            } catch (e: Exception) {
                Log.e(TAG,e.message.toString())
                // 处理其他异常
                e.printStackTrace()
            }
        }
    }

    fun getEventJsonArray(preJsonStr: String):JSONArray{
        var eventConJsonArr = JSONArray()
        try {
            // 截取 `[event]:` 后面的部分
            val jsonStr = preJsonStr.substringAfter("[event]:")

            // 转换为 JSONArray
            eventConJsonArr = JSONArray(jsonStr)
            return eventConJsonArr
        }catch (e: JSONException) {
            Log.e(TAG,e.message.toString())
            // 处理 JSON 解析异常
            e.printStackTrace()
        } catch (e: Exception) {
            Log.e(TAG,e.message.toString())
            // 处理其他异常
            e.printStackTrace()
        }
        return eventConJsonArr
    }

    // 将回调转换为挂起函数
    suspend fun processEvent(preJsonStr: String): Pair<String, JSONObject> {
        return suspendCancellableCoroutine  { cont ->
            onJsonTextEvent(preJsonStr, object : TextEventProcessCallB {
                override fun onEventCallB(eventTypeStr: String, jsonObj: JSONObject) {
                    if (cont.isActive) {
                        Log.d(TAG,"cont.resume1 $eventTypeStr and $jsonObj")
                        cont.resume(Pair(eventTypeStr, jsonObj))
                        Log.d(TAG,"cont.resume2 $eventTypeStr and $jsonObj")
                    }else{
                        Log.d(TAG,"cont is canceled")
                    }
                }
            })
        }
    }
}